<?php

require_once ROOT.DS.'lib' . DS . 'Vendor' . DS . 'qqConnect' . DS . 'qqConnectAPI.php';

/**
 * QQ登录在相同域 。
 * 
 * @author arlon
 *
 */
class QqController extends OauthAppController {

    public $name = 'Qq';

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Hook->loadhook('UCenterHook');
    }

    private function _ucenter_login($user){
        $this->Hook->loadhook('ScoreHook');
        $hook_results = $this->Hook->call('loginSuccess',array($user));
        $login_score = $hook_results['ScoreHook']; unset($hook_results['ScoreHook']); // 积分数不显示在提示消息中
        $user['login_hook_msg'] = implode("\r\n",$hook_results);
        return $user;
    }

    public function login() {
        //$this->Auth->redirect($_SERVER['HTTP_REFERER']);
        $this->Session->write('oauth_referer',$_SERVER['HTTP_REFERER']);
        $qc = new QC();
        $state = $_REQUEST['state'] ? $_REQUEST['state'] : md5(uniqid(rand(), TRUE));
        $qc->qq_login($state);
        exit;
    }

    public function loginCallback() {
        $oauthkeys = $this->Session->read('Auth.QQOauthKeys');
        $qc = new QC();
        $login_token = $this->Session->read('qq_auth_login_token');
        if( $login_token && $login_token['code'] == $_GET['code'] ) {
            $access_token = $login_token['access_token'];
            $open_id = $login_token['open_id'];
            
            $qq_user = $this->Session->read('qq_auth_user');
        }
        else{
            $access_token = $qc->qq_callback();
            $open_id = $qc->get_openid();
            
            $qq_user = $qc->get_user_info();
        }
        
        /*
         * Array
(
    [ret] => 0
    [msg] => 
    [is_lost] => 0
    [nickname] => 齐龙
    [gender] => 男
    [province] => 北京
    [city] => 海淀
    [year] => 1985
    [figureurl] => http://qzapp.qlogo.cn/qzapp/101279123/380CB3EFFDB988A3C7B626B728E2CEB7/30
    [figureurl_1] => http://qzapp.qlogo.cn/qzapp/101279123/380CB3EFFDB988A3C7B626B728E2CEB7/50
    [figureurl_2] => http://qzapp.qlogo.cn/qzapp/101279123/380CB3EFFDB988A3C7B626B728E2CEB7/100
    [figureurl_qq_1] => http://q.qlogo.cn/qqapp/101279123/380CB3EFFDB988A3C7B626B728E2CEB7/40
    [figureurl_qq_2] => http://q.qlogo.cn/qqapp/101279123/380CB3EFFDB988A3C7B626B728E2CEB7/100
    [is_yellow_vip] => 0
    [vip] => 0
    [yellow_vip_level] => 0
    [level] => 0
    [is_yellow_year_vip] => 0
)
         * */
        
        $this->loadModel('User');$this->loadModel('Oauthbind');
        $userinfo = $this->User->find('first', array(
                    'conditions' => array(),
                    'recursive' => -1,
                    'joins' => array(
                        array(
                            'table' => Inflector::tableize('Oauthbind'),
                            'alias' => 'Oauthbind',
                            'type' => 'inner',
                            'conditions' => array(
                                "Oauthbind.user_id = User.id",
                                "Oauthbind.source" => 'qq',
                                "Oauthbind.oauth_openid" => $open_id,
                            ),
                        ),
                    ),
                    'fields' => array('User.*', 'Oauthbind.*'),
                ));
        //print_r($userinfo);exit;
        $current_time = date('Y-m-d H:i:s');
        
        if ($qq_user['gender'] == '男') {
            $gender = 1; //男
        } else {
            $gender = 0; //女
        }
        if (empty($userinfo)) { //该QQ号未绑定过用户。
            
            if($this->currentUser) {
                // 对已登录的用户，直接绑定用户
                $user_id = $this->currentUser['id'];
                $hasbind = $this->Oauthbind->find('first',array( 'conditions' => array('user_id' => $user_id,'source'=>'qq' )));
                if( !empty($hasbind) ){
                	$this->__message('这个登录账号已经绑定过QQ号了，一个绑定只能绑定一个QQ号。');
                }
                
                $this->Oauthbind->deleteAll(array(
                    'oauth_openid' => $open_id,
                    'source' => 'qq',
                )); // 删除可能存在旧的授权。个别用户被后台删除了
                
                $oauth_bind = array(
                    'user_id' => $user_id,
                    'oauth_openid' => $open_id,
                    'oauth_name' => $qq_user['nickname'],
                    'oauth_token' => $access_token,
                    'source' => 'qq',
                );
                $this->Oauthbind->save($oauth_bind);
                
                $this->_success($user_id,$_REQUEST['state']);
                exit;
            }
            else{
                // 第一次使用第三方帐号登录，用户不存在的，要求输入用户名，密码和邮箱。
                /**
                 * Todo. 注册新用户或者绑定以注册用户
                 */
                $this->set('username',$qq_user['nickname']);
                $this->set('headimgurl',$qq_user['figureurl_qq_1']);
                
                $this->Session->write('qq_auth_user', $qq_user);
                $this->Session->write('qq_auth_login_token', array(
                    'access_token'=> $access_token,
                    'open_id' => $open_id,
                    "code" => $_GET['code']
                ));
                return;
            }
            
        } else {	 // QQ号已绑定的用户。
            // 登录成功 
            $updateinfo = array(
                'nickname' => $qq_user['nickname'],
                'screen_name' => $qq_user['nickname'],
                'image' => $qq_user['figureurl_qq_2'] ? $qq_user['figureurl_qq_2'] : $qq_user['figureurl_qq_1'] ,
                'sex' => $gender,
                'location' => $qq_user['location'],
                'last_login' => $current_time,
            );
            
            $userinfo['User'] = array_merge($userinfo['User'], $updateinfo);
            
            $oauth_bind = $userinfo['Oauthbind'];
            
            $user_id = $userinfo['User']['id'];
            $this->User->save($userinfo['User']);
            
            
            $userinfo = $this->User->getUserInfo($userinfo['User']['id']); //重新获取用户信息，保护用户角色等其它内容，避免权限出错。
            
            $this->Session->write('Auth.User', $userinfo['User']);
            $this->Cookie->write('Auth.User', $userinfo['User'], true, 2592000);

            
            $oauth_bind['updated'] = time();
            $oauth_bind['oauth_token'] = $access_token;
            $this->Oauthbind->save($oauth_bind);

            //             $referer =  $this->Session->read('oauth_referer');
            //             $referer ? $url = $referer :  $url='/';
            //$this->redirect($url);
//             $ret = $this->_ucenter_login(array('id'=>$user_id));
            
            $this->_success($user_id,$_REQUEST['state']);
            exit;
        }
    }

    public function register(){
        $this->autoRender = false;
        $qq_user = $this->Session->read('qq_auth_user');
        $login_token = $this->Session->read('qq_auth_login_token');

        if ($qq_user['gender'] == '男') {
            $gender = 1; //男
        } else {
            $gender = 0; //女
        }
        $current_time = date('Y-m-d H:i:s');
        
        $referer =  $this->request->referer();
//         if( empty($this->data['User']['email']) ) {
//         	$this->data['User']['email'] = substr(md5($login_token['open_id']),0,16).'@135editor.com';
//     	}
    	if( $this->data['User']['password'] != $this->data['User']['password_confirm']  ) {
            $this->__message(__('密码与确认密码不一致'), $referer);
        }
        if(empty( $this->data['User']['password'] )){
        	$this->data['User']['password'] = random_str(12);
        }
        
        
        $userinfo = array(
//             'email' => $this->data['User']['email'],
            'password' => Security::hash($this->data['User']['password'], null, true),
            'username' => $qq_user['nickname'],
            'nickname' => $qq_user['nickname'],
            'screen_name' => $qq_user['nickname'],
//				'email'=> $qq_user['profile_image_url'],
            'image' => $qq_user['figureurl_qq_2'] ? $qq_user['figureurl_qq_2'] : $qq_user['figureurl_qq_1'] ,
            'sex' => $gender,
            'role_id' => 2,
            'last_login' => $current_time,
            'created' => $current_time,
            'city' => $qq_user['city'],
            'province' => $qq_user['province'],
            'activation_key' => md5(uniqid()),
            'status' => 1,
        );
        $this->loadModel('User');
        $this->loadModel('Oauthbind');
        if( $this->User->save($userinfo) ) {

            $userinfo['id'] = $user_id = $this->User->getLastInsertID();
            $this->Session->write('Auth.User', $userinfo);
            $this->Cookie->write('Auth.User', $userinfo, true, 2592000);
            
            $this->Oauthbind->deleteAll(array(
                'oauth_openid' => $login_token['open_id'],
                'source' => 'qq',
            )); // 删除可能存在旧的授权。个别用户被后台删除了
            
            $oauth_bind = array(
                'Oauthbind' => array(
                    'user_id' => $user_id,
                    'oauth_openid' => $login_token['open_id'],
                    'oauth_name' => $qq_user['nickname'],
                    'oauth_token' => $login_token['access_token'],
                    'source' => 'qq',
                )
            );
            $this->Oauthbind->save($oauth_bind);
            
            $this->_success($user_id,$_REQUEST['state']);
        }
        else{
            $errors = $this->User->invalidFields();
            print_r($errors);
        }
        exit;

    }
    
    /**
     * 有本站用户，绑定本站用户
     */
    public function bind(){
        
        if( empty($this->data['User']['email']) ) {
            $this->__message(__('邮箱不能为空'), '');
        }
        
        $this->autoRender =  false;
        $this->loadModel('User');
        
        if(Validation::email($this->data['User']['email'])) {
            $userinfo = $this->User->getUserByEmail($this->data['User']['email']);
        }
        else{
            $userinfo = $this->User->getUserByMobile($this->data['User']['email']);
        }
        
        if( !empty($userinfo) && Security::hash($this->data['User']['password'] , null, true) == $userinfo['User']['password'] ) {
            
            $login_token = $this->Session->read('qq_auth_login_token');
            $qq_user = $this->Session->read('qq_auth_user');
            
            $user_id = $userinfo['User']['id'];
            $this->loadModel('Oauthbind');
            $oauth_bind = $this->Oauthbind->find('first', array(
                'conditions' => array(
                    'oauth_openid' => $login_token['open_id'],
                    'user_id' => $user_id,
                    'source' => 'qq',
                ),
            ));
            
            if (empty($oauth_bind)) {
                $oauth_bind = array(
                    'Oauthbind' => array(
                        'user_id' => $user_id,
                        'oauth_openid' => $login_token['open_id'],
                        'oauth_name' => $qq_user['nickname'],
                        'oauth_token' => $login_token['access_token'],
                        'source' => 'qq',
                ));
                $this->Oauthbind->save($oauth_bind);
            } else {
                $oauth_bind['Oauthbind']['updated'] = date('Y-m-d H:i:s');
                $oauth_bind['Oauthbind']['oauth_token'] = $login_token['access_token'];
                $this->Oauthbind->save($oauth_bind);
            }
            $this->Session->write('Auth.User', $userinfo['User']);
            $this->Cookie->write('Auth.User', array(
                'id' => $userinfo['User']['id'],
                'username' => $userinfo['User']['username'],
                'email' => $userinfo['User']['email'],
                'roles' => count($userinfo['User']['role_id']),
            ), true, 2592000);
            
            $this->_success($user_id,$_REQUEST['state']);
        }
        else{
            echo json_encode(array('ret' => -1,'error'=>'Email or password error.'));
        }
        exit;
    }
    
    /**
     * QQ登录，申请开通的域名为www.135editor.com. 需要同步登录 135plat.com
     * @param unknown $user_id
     * @param string $state
     */
    private function _success($user_id,$state=''){
    	$content = '';
    	
    	$appkey = '57326a20-e9cc-461a-8b90-199c9fde689a';
    	$secretKey = 'WYFDXgFMZPFiilBdCWGfqyjSLf1SAsSMG9Pxxz2COLcN';
    	 
    	$ts = time();
    	$u = Security::rijndael($user_id, $secretKey, 'encrypt');
    	 
    	//     	echo Security::rijndael($u, $secretKey, 'decrypt');
    	$u = base64_encode($u);
    	$sign = md5($appkey.$secretKey.$u.$ts);
    	
    	if($state == '135plat'){    		
    		// 从www.135plat.com点开，弹窗打开的是135editor域名登录页。135editor登录成功后，跳转到135plat域名
    		$url = 'http://www.135plat.com/users/login?a=appsync&ts='.$ts.'&appkey='.$appkey.'&u='.urlencode($u).'&sign='.$sign;
    		$this->redirect($url);
    	}
    	else{
//     		$isvip = false;
//     		if(substr($state,0,3)=='vip') {
//     			$isvip = true;
//     			$state = substr($state,3);
//     			$url = 'http://vip.135editor.com/users/login?a=appsync&ts='.$ts.'&appkey='.$appkey.'&u='.urlencode($u).'&sign='.$sign;
//     			$this->redirect($url);
//     		}
    		// 从www.135editor.com登录后，需要同步登录135plat
    		if($state == 'postmsg'){
    			// 通过ajax重新调用login操作，实现加载用户信息以及提示登录
    			$content = '已成功登录,窗口将自动关闭。<script>document.domain="135editor.com";window.opener.postMessage("loginSuccess","*");window.close();</script>';
    		}
    		else{
    			$url = 'http://www.135plat.com/users/login?a=appsync&ts='.$ts.'&appkey='.$appkey.'&u='.urlencode($u).'&state='.$state.'&sign='.$sign;
    			$this->Session->setFlash( __('Login Success').'<script type="text/javascript" src="'.$url.'"></script>');
	    		$content = '已成功登录,窗口将自动关闭。<script>document.domain="135editor.com";window.opener.location.reload(true);window.close();</script>';
	    	}
    	}
    	$this->response->body($content);
    	$this->response->send();
    	exit;
    }

}

?>